
#include "SHT20.h"

int SHT20_Measure(double *temperature, double *humidity) 
{

	  uint8_t buf[2];
    HAL_StatusTypeDef rv;
		uint8_t cmd = SHT20_TEMP_CMD;//测量温度
 
    // 发送测量命令
    rv = HAL_I2C_Master_Transmit(&hi2c1, SHT20_ADDRESS << 1, &cmd, 1, HAL_IIC_DELAY);
    if (rv != HAL_OK) return -1;
 
		HAL_Delay(85); // 测量延迟
 
    // 接收测量数据
    rv = HAL_I2C_Master_Receive(&hi2c1, (SHT20_ADDRESS << 1) | 0x01, buf, 2, HAL_IIC_DELAY);
    if (rv != HAL_OK) return -1;
	 
    // 计算温度值
    *temperature = -46.85 + 175.72 * ((buf[0] << 8 | buf[1]) / 65536.0);
	
		cmd = SHT20_RH_CMD;//测量湿度
		
	    // 发送测量命令
    rv = HAL_I2C_Master_Transmit(&hi2c1, SHT20_ADDRESS << 1, &cmd, 1, HAL_IIC_DELAY);
    if (rv != HAL_OK) return -1;
 
		HAL_Delay(41); // 测量延迟
 
    // 接收测量数据
    rv = HAL_I2C_Master_Receive(&hi2c1, (SHT20_ADDRESS << 1) | 0x01, buf, 2, HAL_IIC_DELAY);
    if (rv != HAL_OK) return -1;

    // 计算湿度值
    *humidity = -6.0 + 125.0 * ((buf[0] << 8 | buf[1]) / 65536.0);

		return 0;
}
//void lighttest(double *light_num)
//{
//	int i;
//	uint8_t buf[6];
//	unsigned short ir,als,ps;
//	uint8_t cmd = AP3216C_SW_RESET;
//	HAL_I2C_Master_Transmit(&hi2c1, AP3216C_ADDR << 1, &cmd, 1, HAL_IIC_DELAY);
//	HAL_Delay(50);

//	cmd = AP3216C_SW_ALS;
//	HAL_I2C_Master_Transmit(&hi2c1, AP3216C_ADDR << 1, &cmd, 1, HAL_IIC_DELAY);
//	HAL_Delay(50);

//	HAL_I2C_Master_Receive(&hi2c1, AP3216C_ADDR << 1, buf, 6,HAL_IIC_DELAY);

//    if (buf[0] & 0x80) {
//        ir = 0;
//    } else {
//        ir = ((unsigned short)buf[1] << 2) | (buf[0] & 0x03);
//        als = ((unsigned short)buf[3] << 8) | buf[2];
//    }
// 
//    if (buf[4] & 0x40) {
//        ps = 0;
//    } else {
//        ps = ((unsigned short)(buf[5] & 0x3F) << 4) | (buf[4] & 0x0F);
//    }
//		*light_num = als;
//	u1_USART("buf =%s\r\n",buf);
//	u1_USART("ALS:%u ,PS:%u ,IR:%u \\r\\n",als,ps,ir);
// }
